package com.ittx.dzt.weidian.service;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.ittx.dzt.edi.constant.GeneralConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.weidian.constant.WeidianApiConstant;
import com.ittx.dzt.weidian.handler.AbstractWeidianByTimeApiHandler;
import com.ittx.dzt.weidian.util.CyUtil;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 售后单增量下载
 * <p>
 * cy.returnOrder.download.byTimeFrame
 * 逆向-退款列表(open.SellerQueryRefundList) https://open.weidian.com/#/api/1073
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/3/25
 */
@Slf4j
@Service
public class WeidianReturnOrderDownloadByTimeService extends AbstractWeidianByTimeApiHandler<TimeFrameDTO> {

	private static final Integer DEFAULT_PAGE_SIZE = 50;

	@Autowired
	private WeidianReturnOrderDownloadByIdService weidianReturnOrderDownloadByIdService;

	@Override
	public String getWeidianMethod() {
		return "open.SellerQueryRefundList";
	}

	@Override
	public String getWeidianApiVersion() {
		return "2.0";
	}

	@Override
	public String getWeidianApiFormat() {
		return "json";
	}

	@Override
	protected String getMqTopic() {
		return WeidianApiConstant.Rocket.WEIDIAN_DOWNLOAD_AFTERSALE_LIST_BY_TIME_BATCH_SPLIT_TOPIC;
	}


	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.RETURNORDER_DOWNLOAD_BY_TIMEFRAME;
	}

	@Override
	protected Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//分发数据,异步下载
		Map<String, Boolean> logMap = new HashMap<>();
		// 判断是rds还是sdk
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		// sdk
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);
	}

	@Override
	protected Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		// 探查成功时不返回完整数据,只返回数量
		// 判断是rds还是sdk
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);

	}

	/**
	 * rds直接批量下载后下发，不经过拆分队列
	 *
	 * @param platformApiParamDTO
	 * @param timeFrameDTO
	 * @return
	 */
	@Override
	protected Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		String refundId = platformApiParamDTO.getPlatformIdentifierTag();
		return this.asyncHandlerById(platformApiParamDTO, String.valueOf(refundId));

	}

	/**
	 * sdk
	 * 请求平台接口
	 */
	private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {
		Map<String, Object> params = new HashMap<>();
		params.put("updateTimeStart", timeFrameDTO.getFrom().format(DateTimeFormatter.ofPattern(GeneralConstant.DEFAULT_DATE_TIME_PATTERN)));
		params.put("updateTimeEnd", timeFrameDTO.getTo().format(DateTimeFormatter.ofPattern(GeneralConstant.DEFAULT_DATE_TIME_PATTERN)));
		params.put("pageSize", DEFAULT_PAGE_SIZE);
		// 状态过滤
		List<Integer> statusList = CyUtil.getStatusList(platformApiParamDTO, "return");
		if (CollectionUtil.isNotEmpty(statusList)) {
			// 退款状态 1-创建退款，3-拒绝退款，4-同意退货，5-拒绝退货，6-逆向发货，9-逆向取消，10-逆向完成（同意退款）
			params.put("statusList", statusList);
		}

		long page = 0;
		// 第一次查询，获取总页数
		params.put("pageNum", page);
		Result<?> result = this.executeWeidianApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
		if (!result.isSuccess()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("result");
		// 售后单总数
		Integer total = MapUtil.getInt(dataMap, "totalNum", 0);
		// 探查模式只返回总数
		if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
			return Result.success().addData(total);
		}
		Integer totalPage = this.totalPage(total, DEFAULT_PAGE_SIZE);
		if (totalPage > 0) {
			// 倒序查询，防止漏单
			for (int i = totalPage - 1; i >= 0; i--) {
				params.put("pageNum", i);
				result = this.executeWeidianApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
				if (!result.isSuccess()) {
					return result;
				}
				resultMap = (Map<String, Object>) result.getData();
				dataMap = (Map<String, Object>) resultMap.get("result");
				List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("list");
				if (CollectionUtil.isNotEmpty(list)) {
					for (Map<String, Object> refund : list) {
						String refundId = refund.get("refund_no") + "";
						sendToSplitTopic(platformApiParamDTO, refundId, logMap);
					}
				}
			}
		}
		return Result.success(logMap);
	}

	/**
	 * sdk
	 * <p>
	 * 根据订单号下载售后单 ------- 多线程执行
	 */
	@Override
	public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String refundId) {
		Result<?> result = weidianReturnOrderDownloadByIdService.getRefundById(platformApiParamDTO, refundId);
		if (!result.isSuccess()) {
			return result;
		}
		return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
	}


}
